package client_commands

import scala.actors.Actor
import scala.actors.Actor._
import scala.actors.remote.Node
import scala.actors.remote.RemoteActor
import scala.actors.remote.RemoteActor._
import objects.File2
import db.Client
import executors.ChangedFileExecutor
import client_updater.ClientsUpdater
import client_updater.FileUpdate


/**
 * Listens to updates about files that were changed in a client's dropbox.<br>
 * Works as a remote actor that listens to messages on a given port.<br>
 * @param - port to listen on.<br>
 * @param - executor : Actor 
 */
class ChangedFileActor(port: Int, executor : Actor) extends Actor {

  /**
   * The acting method of the actor.<br>
   * Receives messages about files that were changed in a client's 
   * dropbox and then sends <br>
   * the information forwards to be processed against the data-base, 
   * the disk, and other clients.
   */
  def act() {
    alive(port)
    register('ChangedFile, self)

    loop {
      react {
        case (uid : Long, cid : Long, name : String, parent : Long, size : Long, code :Long) =>
          {
            val changedFile = new File2(uid, cid, name, parent, size, code)
            println("Processing changed file "+name)
            var result = (executor !? (changedFile: File2))
            if (result == false) {
              var client = new Client
              client.setUserID(changedFile.uid)
              client.setClientID(changedFile.cid)
              var bytes = null.asInstanceOf[Array[Byte]] //TO DO: get the bytes!!!
              ClientsUpdater.addUpdate(cid, new FileUpdate(
                "upload", changedFile.name, changedFile.parent, code))
            }
          }
        case "Quit" => {
          println("changedFileActor stopped")
          executor ! "Quit"
          exit()
        }
        case _ =>
          println("changedFileActor received unknown message")
      }
    }
  }
}
